package org.particlethink.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.particlethink.auth.DefaultUser;
import org.particlethink.entry.PlanStatus;
import org.particlethink.model.User;
import org.particlethink.request.*;
import org.particlethink.response.*;
import org.particlethink.service.procure.ProjectUserImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Tag(name = "批次计划")
@RestController
@RequestMapping("/batch_plan")
public class BatchPlanController {
    @Autowired
    ProjectUserImpl projectUserSvc;

    @Operation(summary = "批次计划列表")
    @GetMapping
    public BaseResponse<PageInfo<BatchPlanResponse>> List(
            @Parameter(description = "管理层级 string")
            @RequestParam(value = "managementLevel", required = false)
            String managementLevel,

            @Parameter(description = "项目id int")
            @RequestParam(value = "projectId", required = false)
            Integer projectId,

            @Parameter(description = "批次计划单号 string")
            @RequestParam(value = "batchPlanNo", required = false)
            String batchPlanNo,

            @Parameter(description = "总计划单号 string")
            @RequestParam(value = "masterPlanNo", required = false)
            String masterPlanNo,

            @Parameter(description = "物料大类名 string")
            @RequestParam(value = "categoryName", required = false)
            String categoryName,

            @Parameter(description = "状态 int 1:待提交；2：已提交；3：已作废")
            @RequestParam(value = "status", required = false)
            PlanStatus status,

            @Parameter(description = "提交开始时间 string yyyy-MM-dd HH:mm:ss")
            @RequestParam(value = "submitStart", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            Date submitStart,
            @Parameter(description = "提交结束时间 string")
            @RequestParam(value = "submitEnd", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            Date submitEnd,
            @Parameter(description = "最晚到货日期开始时间 string")
            @RequestParam(value = "deadlineStart", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            Date deadlineStart,

            @Parameter(description = "最晚到货日期开始时间 string")
            @RequestParam(value = "deadlineEnd", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            Date deadlineEnd,

            @Parameter(description = "页码 int")
            @RequestParam(value = "pageNum", required = false)
            Integer pageNum,
            @Parameter(description = "每页数量 int")
            @RequestParam(value = "pageSize", required = false)
            Integer pageSize
    ) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();

        return BaseResponse.success(projectUserSvc.batchPlanList(
                user,
                managementLevel,
                projectId,
                masterPlanNo,
                batchPlanNo,
                categoryName,
                status,
                submitStart,
                submitEnd,
                deadlineStart,
                deadlineEnd,
                pageNum,
                pageSize
        ));
    }


    @Operation(summary = "导出批次计划台账")
    @GetMapping("/export")
    public void export(
            @Parameter(description = "管理层级 string")
            @RequestParam(value = "managementLevel", required = false)
            String managementLevel,

            @Parameter(description = "项目id Integer")
            @RequestParam(value = "projectId", required = false)
            Integer projectId,

            @Parameter(description = "批次计划单号 string")
            @RequestParam(value = "batchPlanNo", required = false)
            String batchPlanNo,

            @Parameter(description = "总计划单号 string")
            @RequestParam(value = "masterPlanNo", required = false)
            String masterPlanNo,

            @Parameter(description = "物料大类名 string")
            @RequestParam(value = "categoryName", required = false)
            String categoryName,

            @Parameter(description = "状态 int 1:待提交；2：已提交；3：已作废")
            @RequestParam(value = "status", required = false)
            PlanStatus status,

            @Parameter(description = "提交开始时间 string yyyy-MM-dd HH:mm:ss")
            @RequestParam(value = "submitStart", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            Date submitStart,
            @Parameter(description = "提交结束时间 string")
            @RequestParam(value = "submitEnd", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            Date submitEnd,
            @Parameter(description = "最晚到货日期开始时间 string")
            @RequestParam(value = "deadlineStart", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            Date deadlineStart,

            @Parameter(description = "最晚到货日期开始时间 string")
            @RequestParam(value = "deadlineEnd", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            Date deadlineEnd,
            HttpServletResponse response
    ) throws IOException {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();

        List<BatchPlanExportResponse> batchPlanResponses = projectUserSvc.batchPlanExport(
                user,
                managementLevel,
                projectId,
                masterPlanNo,
                batchPlanNo,
                categoryName,
                status,
                submitStart,
                submitEnd,
                deadlineStart,
                deadlineEnd
        );

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("批次计划", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        EasyExcel.write(response.getOutputStream(), BatchPlanExportResponse.class).sheet("模板").doWrite(batchPlanResponses);
    }

    @Operation(summary = "批次计划详情")
    @GetMapping("/{id}")
    public BaseResponse<BatchPlanDetailResponse> Show(@PathVariable("id") Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();

        BatchPlanDetailResponse batchPlanDetailResponse = projectUserSvc.batchPlanDetail(user,id);
        return BaseResponse.success(batchPlanDetailResponse);
    }

    @Operation(summary = "创建批次计划")
    @PostMapping
    public BaseResponse<String> Create(@RequestBody BatchPlanRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();

        projectUserSvc.createBatchPlan(user, request);

        return BaseResponse.success("");
    }

    @Operation(summary = "提交批次计划")
    @PostMapping("/{id}/submit")
    public BaseResponse<String> Submit(@PathVariable("id") Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();


        projectUserSvc.submitBatchPlan(user.getProjectIds(), user.getUserId(), id);

        return BaseResponse.success("");
    }

    @Operation(summary = "修改批次计划")
    @PatchMapping("/{id}")
    public BaseResponse<String> edit(@RequestBody BatchPlanRequest request, @PathVariable("id") Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();


        projectUserSvc.updateBatchPlan(user.getProjectIds(), id, request);
        return BaseResponse.success("");
    }


    @Operation(summary = "删除批次计划")
    @DeleteMapping("/{id}")
    public BaseResponse<String> delete(@PathVariable("id") Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();

        projectUserSvc.deleteBatchPlan(user.getProjectIds(), id);

        return BaseResponse.success("");
    }

    @Operation(summary = "撤回批次计划")
    @PostMapping("/{id}/cancel")
    public BaseResponse<String> cancel(@PathVariable("id") Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();

        projectUserSvc.cancelBatchPlan(user.getProjectIds(), id);

        return BaseResponse.success("");
    }


    @Operation(summary = "作废批次计划")
    @PostMapping("/{id}/discard")
    public BaseResponse<String> discard(@PathVariable("id") Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();


        projectUserSvc.discardBatchPlan(user.getProjectIds(), id);

        return BaseResponse.success("");
    }


    @Operation(summary = "启用批次计划")
    @PostMapping("/{id}/enable")
    public BaseResponse<String> enable(@PathVariable("id") Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();


        projectUserSvc.enableBatchPlan(user.getProjectIds(), id);

        return BaseResponse.success("");
    }


    @Operation(summary = "导入物料")
    @PostMapping("/import/material")
    public BaseResponse<List<ImportMaterialResponse>> ImportMaterial(@RequestParam("file") MultipartFile file) throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();

        ExcelListener<MasterBatchMaterialRequest> excelListener = new ExcelListener<>();
        EasyExcel.read(file.getInputStream(), MasterBatchMaterialRequest.class, excelListener).sheet("导入填写").doRead();
        List<MasterBatchMaterialRequest> requests = excelListener.getData();

        if (requests.size() <= 1) {
            return BaseResponse.success(new ArrayList<>());
        }

        requests.remove(0);


        List<ImportMaterialResponse> materialResponses = this.projectUserSvc.ImportMaterialPlan(user,requests);

        return BaseResponse.success(materialResponses);

    }
}
